package com.tsd.core.utils;

import com.tsd.core.config.Config;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import net.xpyun.platform.opensdk.service.XpyunPrintService;
import net.xpyun.platform.opensdk.util.XpyunConfig;
import net.xpyun.platform.opensdk.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 芯烨云打印机工具栏
 * 见包net.xpyun.platform.opensdk下面的内容
 * <a href="https://www.xpyun.net/index.html">...</a>
 *
 * @author huawei
 * @date 2022/04/16 12:16:55
 */
public class XpYunPrinterUtil {
    public static final Logger LOGGER = LoggerFactory.getLogger(XpYunPrinterUtil.class);
    //config.xml内的参数名
    public static final String PARAMS_NAME_XPYUN_PARAM_USER_NAME = "xpyun_user_name";
    public static final String PARAMS_NAME_XPYUN_PARAM_USER_KEY = "xpyun_user_key";
    //声音播放模式，0 为取消订单模式，1 为静音模式，2 为来单播放模式，3为有用户申请退单了。默认为 2 来单播放模式
    public static final int VOICE_MODE_CANCEL = 0;
    public static final int VOICE_MODE_SILENT = 1;
    public static final int VOICE_MODE_ORDER = 2;
    public static final int VOICE_MODE_USER_CANCEL = 3;
    private static final Map<Integer, String> STAT_MAP;

    static {
        STAT_MAP = new HashMap<>();
        STAT_MAP.put(1, "在线正常");
        STAT_MAP.put(2, "在线缺纸");
        STAT_MAP.put(0, "离线");
    }

    static public String getStatusText(Integer key) {
        if (STAT_MAP != null) {
            return STAT_MAP.get(key);
        } else {
            return null;
        }
    }

    /**
     * 注册芯烨云打印机
     *
     * @param printer_sn
     * @param printer_name
     * @return
     */
    public static HttpResult<Object> regXpYunPrinter(String printer_sn, String printer_name) {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            AddPrinterRequest request = new AddPrinterRequest();
            // 添加公共参数
            XpyunConfig.createRequestHeader(request, Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_NAME), Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_KEY));
            //打印机列表
            List<AddPrinterRequestItem> itemList = new ArrayList<>();
            AddPrinterRequestItem item = new AddPrinterRequestItem();
            item.setSn(printer_sn);
            item.setName(printer_name);
            itemList.add(item);
            //*必填*：items:数组元素为 json 对象：
            //{"name":"打印机名称","sn":"打印机编号"}
            //其中打印机编号 sn 和名称 name 字段为必填项，每次最多添加50台
            AddPrinterRequestItem[] items = new AddPrinterRequestItem[itemList.size()];
            itemList.toArray(items);
            request.setItems(items);
            ObjectRestResponse<PrinterResult> resp = XpyunPrintService.addPrinters(request);
            //resp.data:返回1个 json 对象，包含成功和失败的信息，详看https://www.xpyun.net/open/index.html示例
            boolean ok = false;
            StringBuilder buf = new StringBuilder();
            if (resp.getCode() == 0) {
                if (resp.getData() != null) {
                    if (resp.getData().getSuccess() != null && !resp.getData().getSuccess().isEmpty()) {
                        hr.setCode(ErrorCode.CODE_SUCCESS);
                        ok = true;
                    } else {
                        List<String> failMsg = resp.getData().getFailMsg();
                        for (String s : failMsg) {
                            String[] keyvalue = s.split(":");
                            if (keyvalue.length > 1) {
                                if (!"0".equals(keyvalue[0])) {
                                    String txt = XpYunResponseState.getStateText(keyvalue[1]);
                                    if (!HlpUtils.isEmpty(txt)) {
                                        buf.append(txt);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!ok || buf.length() > 0) {
                hr.setCode(ErrorCode.CODE_PROC_ERROR);
                if (buf.length() > 0) {
                    hr.setMessage(buf.toString());
                } else {
                    hr.setMessage(resp.getMsg());
                }
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
            hr.setMessage(e.getMessage());
            hr.setCode(ErrorCode.CODE_PROC_ERROR);
        }
        return hr;
    }

    public static HttpResult<Object> delXpYunPrinter(String printer_sn) {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            DelPrinterRequest request = new DelPrinterRequest();
            XpyunConfig.createRequestHeader(request, Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_NAME), Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_KEY));
            //*必填*：打印机编号集合，类型为字符串数组
            String[] snlist = new String[1];
            //*必填*：打印机编号
            snlist[0] = printer_sn;
            request.setSnlist(snlist);
            ObjectRestResponse<PrinterResult> resp = XpyunPrintService.delPrinters(request);
            boolean ok = false;
            StringBuilder buf = new StringBuilder();
            if (resp.getCode() == 0) {
                if (resp.getData() != null) {
                    if (resp.getData().getSuccess() != null && !resp.getData().getSuccess().isEmpty()) {
                        hr.setCode(ErrorCode.CODE_SUCCESS);
                        ok = true;
                    } else {
                        List<String> failMsg = resp.getData().getFailMsg();
                        for (String s : failMsg) {
                            String[] keyvalue = s.split(":");
                            if (keyvalue.length > 1) {
                                if (!"0".equals(keyvalue[0])) {
                                    String txt = XpYunResponseState.getStateText(keyvalue[1]);
                                    if (!HlpUtils.isEmpty(txt)) {
                                        buf.append(txt);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!ok || buf.length() > 0) {
                hr.setCode(ErrorCode.CODE_PROC_ERROR);
                if (buf.length() > 0) {
                    hr.setMessage(buf.toString());
                } else {
                    hr.setMessage(resp.getMsg());
                }
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
            hr.setMessage(e.getMessage());
            hr.setCode(ErrorCode.CODE_PROC_ERROR);
        }
        return hr;
    }

    /**
     * 打印是否完成
     *
     * @param printer_sn
     * @param print_sn
     * @return
     * @throws Exception
     */
    public static boolean hasOrderPrinted(String printer_sn, String print_sn) throws Exception {
        QueryOrderStateRequest request = new QueryOrderStateRequest();
        XpyunConfig.createRequestHeader(request, Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_NAME), Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_KEY));
        // *必填*：订单编号，由“打印订单”接口返回
        request.setOrderId(print_sn);
        ObjectRestResponse<Boolean> resp = XpyunPrintService.queryOrderState(request);
        //resp.data:返回布尔类型,已打印返回true,未打印返回false
        return resp.getData();
    }

    /**
     * 查询云打印机状态
     * //0 表示离线
     * //1 表示在线正常
     * //2 表示在线缺纸
     *
     * @param snList
     * @return
     */
    public static List<Integer> queryPrintersStatus(List<String> snList) {
        PrintersRequest request = new PrintersRequest();
        XpyunConfig.createRequestHeader(request, Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_NAME), Config.getParameterValue(PARAMS_NAME_XPYUN_PARAM_USER_KEY));
        //*必填*：打印机编号
        request.setSnlist(snList);
        ObjectRestResponse<List<Integer>> resp = XpyunPrintService.queryPrintersStatus(request);
        //resp.data:返回打印机状态值，共三种：
        //0 表示离线
        //1 表示在线正常
        //2 表示在线缺纸
        //备注：离线的判断是打印机与服务器失去联系超过 30 秒
        if (resp != null && resp.getData() != null) {
            return resp.getData();
        } else {
            return null;
        }
    }
}
